﻿using System;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace Agile.VSIX {
    internal static class OutputWindowHelper
    {
        #region Fields

        private static IVsOutputWindowPane _codeMaidOutputWindowPane;

        #endregion Fields

        #region Properties

        private static IVsOutputWindowPane CodeMaidOutputWindowPane =>
            _codeMaidOutputWindowPane ?? (_codeMaidOutputWindowPane = GetCodeMaidOutputWindowPane());

        #endregion Properties

        #region Methods
        internal static void DiagnosticWriteLine(string message, Exception ex = null)
        {
            if (ex != null)
            {
                message += $": {ex}";
            }

            WriteLine("诊断", message);
        }
        internal static void ExceptionWriteLine(string message, Exception ex)
        {
            var exceptionMessage = $"{message}: {ex}";

            WriteLine("异常", exceptionMessage);
        }
        internal static void WarningWriteLine(string message)
        {
            WriteLine("警告", message);
        }
        private static IVsOutputWindowPane GetCodeMaidOutputWindowPane()
        {
            if (!(Package.GetGlobalService(typeof(SVsOutputWindow)) is IVsOutputWindow outputWindow))
            {
                return null;
            }
            Guid outputPaneGuid = new Guid();
            outputWindow.CreatePane(ref outputPaneGuid, "AgileVsix", 1, 1);
            outputWindow.GetPane(ref outputPaneGuid, out IVsOutputWindowPane windowPane);

            return windowPane;
        }
        private static void WriteLine(string category, string message)
        {
            var outputWindowPane = CodeMaidOutputWindowPane;
            if (outputWindowPane != null)
            {
                string outputMessage = $"[AgileVsix {category} {DateTime.Now.ToString("hh:mm:ss tt")}] {message}{Environment.NewLine}";

                outputWindowPane.OutputString(outputMessage);
            }
        }

        #endregion Methods
    }
}